#include "BrainProducts.h"

#define PORT_NUMBER		51234



BrainProducts::BrainProducts(void)
{
	wxTextFile	File;
	wxString	Server;
	Instrument::Instrument();
	
	
	MyName = _("BrainProducts");
	//memset(Filters,0,sizeof(Filters));
	/*if(File.Open(_T("./ConfigDevices/BrainProducts.txt")))
	{
		Server	=	File.GetLine(1);
		strcpy(pszHost,Server.ToAscii());
	}*/
	BrainVisionOn = false;
}

BrainProducts::~BrainProducts(void)
{

}

//Prima dell'entry va sempre chiamato Initialize
void* BrainProducts::Entry(void)
{
	int nChannels = NULL;
	float Frequency = NULL;
	int		nLastBlock = 0;

	Esci = false;
	while(!Esci)
	{
		RDA_MessageHeader* pHeader = NULL;
		int nResult = GetServerMessage(hSocket, &pHeader);
		if (nResult > 0)	// New message?
		{
			RDA_MessageStart* pMsgStart = NULL;
			RDA_MessageData* pMsgData = NULL;
			switch(pHeader->nType)
			{
			case 2:			// Data
				pMsgData = (RDA_MessageData*)pHeader;
				// Simple overflow test
				if (nLastBlock != -1 && pMsgData->nBlock > nLastBlock + 1)
					SetMessage(_("******* Overflow ******\n"));
				nLastBlock = pMsgData->nBlock;
				if(IsPlotting)		
					ProcessDataMessage(pMsgData);

				break;

			case 3:			// Stop
				printf("Stop\n");
				break;

			default:
				// Ignore all unknown types!
				Sleep(1);
				break;
			}
			if (pHeader) free(pHeader);
		}else if (nResult == -2)
		{
			SetMessage(_("Server has closed the connection.\n"));
			Esci = true;
		}else if (nResult < 0)
		{
			SetMessage(_("An error occured during message receiving.\n"));
			Esci = true;
		}
	}
	closesocket(hSocket);
	hSocket = NULL;
	return NULL;
}

void BrainProducts::ProcessDataMessage(RDA_MessageData* pMsgData )
{
	int u,i;
	float temp;
	SampleStruct	Signal;
	memset(&Signal,0,sizeof(Signal));
	Signal.Data.DataLen	=	Channels;

	for(u=0;u<(int)(pMsgData->nPoints);u++)
	{
		for(i=0;i<Channels;i++)
		{
			temp = pMsgData->nData[i+u*Channels];
			Signal.Data.Signal[i]=temp;
		}
		PutSample(&Signal);
	}
}
void BrainProducts::StartDevice(wxString FileName,wxString FilePath,bool File)
{
//	wxASSERT (m_pSocket);
	Instrument::StartDevice(FileName,FilePath,File);
	IsPlotting = true;
	/*if(!IsRunning)
	{
		SendCommand(ClientControlCode,RequestStartData);
		IsRunning=true;
	}*/
}

void BrainProducts::StopDevice(void)
{
	IsPlotting = false;
	Esci = true;
	Instrument::StopDevice();
}
int BrainProducts::OpenPort(const char *pszHost, const char *OpenVal2, const char *OpenVal3)
{
	WSADATA wsaData;
	WSAStartup(2, &wsaData);

	sockaddr_in addr;

	IsPlotting = false;
	
	hSocket = socket(PF_INET, SOCK_STREAM, 0);
	if (hSocket == SOCKET_ERROR)
	{
		SetMessage(_("Error: can't create socket!\n"));
		return -1;
	}

	char TempLabel[200];
	BOOL bTCP_NODELAY = TRUE;

	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT_NUMBER);
	
	hostent* pHost = gethostbyname(pszHost);
	if (pHost == NULL)
	{
		closesocket(hSocket);
		SetMessage(_("Can't find host!\n"));
		return -1;
	}
	if (pHost->h_addr_list == 0)
	{
		closesocket(hSocket);
		SetMessage(_("Can't initialize Remote Data Access.\n"));
		return -1;
	}

	addr.sin_addr = **((in_addr**)(pHost->h_addr_list));

	if (connect(hSocket, (sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) 
	{
		closesocket(hSocket);
		SetMessage(_("Can't connect to server.\n"));
		return -1;
//		exit(1);
	}
	else
	{
	int		nLastBlock;
	int nChannels = NULL;
	char* pszChannelNames;
	float Period;
	float Frequency = NULL;
	
	//Open dialog
	WaitDlg WaitConnection(NULL, hSocket);
	WaitConnection.ShowModal();
			
	RDA_MessageStart* pMsgStart = NULL;
	RDA_MessageData* pMsgData = NULL;
	if (WaitConnection.pHeader == NULL)
		return -1;
			
	pMsgStart = (RDA_MessageStart*)WaitConnection.pHeader;
	// Retrieve number of channels.
	nChannels	=	pMsgStart->nChannels;
	Period		=	pMsgStart->dSamplingInterval;
	Frequency	=	1000000.0f/Period;
	Resolution	=	pMsgStart->dResolutions[0];
	DigitalMax		=	65536; //16bit
	DigitalMin		=	0;
	DigitalOffset	=	0;//65536/2;
	Message = wxString::Format(_("Start Received %d channels %.2f Hz frequency\n"),nChannels,Frequency);
	//SetMessage(wxString::Format(_("Start Received %d channels %.2f Hz frequency\n"),nChannels,Frequency));
	pszChannelNames = (char*)pMsgStart->dResolutions + nChannels * sizeof(pMsgStart->dResolutions[0]);
	for(int i=0;i<nChannels;i++)
	{

		sprintf(TempLabel,"%s",pszChannelNames);
		Labels[i] = wxString::FromAscii(TempLabel);
		pszChannelNames += strlen(pszChannelNames) + 1;
	}
	nLastBlock = -1;
	Message += wxT("Connection completed!\n");
	//SetMessage(_("Connection completed!\n"));	
	SetMessage(Message);
	Sleep(100);
	Initialize(nChannels,Frequency,20);
	}

	return 1;
}

